package com.open.web.filter;


import com.open.basic.BaseRequestHeader;
import com.open.basic.constant.RequestHeaderConst;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author: codex
 * @Date: 2024/4/21 10:19
 * @Version: V1.0
 * @description: desc:将请求头的参数放入RequestHeader里
 */
@WebFilter
@Order(1)
@Component("appendParametersFilter")
public class AppendParametersFilter implements Filter {
//    @Autowired
//    private RedisUtil redisUtil;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        ParameterRequestWrapper requestWrapper = new ParameterRequestWrapper((HttpServletRequest) request);

        // 请求的参数 拼接
        BaseRequestHeader header = convertMap(request);
//        // 请求参数 body
//        Set<String> keySet = rtnMap.keySet();
//        //解密value
//        for (String str : keySet) {
//            String value = rtnMap.get(str);
//            // 将参数追加到request url 之后
//            requestWrapper.addParameter(str, value);
//            // 将参数追加到request 的body 中
//            requestWrapper.addParameterToBody(str, value);
//        }
        requestWrapper.addParameterToBody("baseRequestHeader", header);
        // 过滤链调用
        chain.doFilter(requestWrapper, response);
    }

    /**
     * 转换request 请求参数并追加要添加的参数
     *
     * @param request
     */
    public BaseRequestHeader convertMap(ServletRequest request) {
        HttpServletRequest request1 = (HttpServletRequest) request;
        String userId = request1.getHeader(RequestHeaderConst.USER_ID);
        // String username = request1.getHeader(RequestHeaderConst.USERNAME);
        // 获取请求id 用于接口幂等判断
        String requestId = request1.getHeader(RequestHeaderConst.REQUEST_ID);
        String accessToken = request1.getHeader(RequestHeaderConst.ACCESS_TOKEN);
        String refreshToken = request1.getHeader(RequestHeaderConst.REFRESH_TOKEN);
        BaseRequestHeader requestHeader = new BaseRequestHeader();
        requestHeader.setUserId(userId);
        // requestHeader.setUsername(username);
        requestHeader.setToken(accessToken);
        requestHeader.setRequestId(requestId);
        return requestHeader;
    }
}


